package com.stars.empoly.base

import android.content.Context
import android.os.IBinder
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.databinding.ViewDataBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.stars.empoly.R
import com.stars.empoly.activity.LoginActivity
import com.stars.empoly.activity.OneLoginActivity
import com.stars.empoly.model.User
import com.trailer.base.base.BRActivity
import com.trailer.base.base.BRViewModel
import com.trailer.base.inter.IUser
import com.trailer.base.utils.UiSwitch

/**
 * Mine Base BRView Activity
 *
 * @param <VM>
 * @param <A>
 * @param <B>
</B></A></VM> */
abstract class MBRActivity<VM : BRViewModel<*>, A : BaseQuickAdapter<*, out BaseViewHolder>, B : ViewDataBinding> : BRActivity<VM, A, B>() {
    override fun toLogin() {
        super.toLogin()
        UiSwitch.single(context(), OneLoginActivity::class.java)
//     toast(R.string.please_login)
    }

    override fun user(): IUser? {
        return User.get()
    }

    override fun bgColor(): Int {
        return R.color.white
    }

    override fun titleColor(): Int {
        return R.color.black
    }

    override fun backDrawable(): Int {
        return R.drawable.ic_back_black
    }

    override fun rightTextColor(): Int {
        return R.color.black
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev!!.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v!!.windowToken)
            }
        }
        return super.dispatchTouchEvent(ev)
    }



    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    fun hideKeyboard(token: IBinder?) {
        if (token != null) {
            val im = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }


}
